package com.example.config;

import com.example.swagger.SwaggerAutoConfiguration;
import org.hibernate.validator.HibernateValidator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;

/**
 * @author liheng
 * @ClassName ValidatorConf
 * @Description 校验模式
 * 在上面的例子中，我们使用BindingResult验证不通过的结果集合，但是通常按顺序验证到第一个字段不符合验证要求时，就可以直接拒绝请求了。这就涉及到两种校验模式的配置：
 * <p>
 * 普通模式（默认是这个模式）: 会校验完所有的属性，然后返回所有的验证失败信息
 * 快速失败模式: 只要有一个验证失败，则返回
 * 如果想要配置第二种模式，需要添加如下配置类：
 * @date 2019/12/27 14:56
 * @Version 1.0
 */
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    @Autowired
    private UserAuthInterceptor userAuthInterceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // pc 端拦截
        registry.addInterceptor(userAuthInterceptor)
                // 拦截所有请求
                .addPathPatterns("/**")
                .excludePathPatterns("/login")
                .excludePathPatterns("/load")
                .excludePathPatterns(SwaggerAutoConfiguration.DOC_LIST);

    }


    @Bean
    public Validator validator() {
        ValidatorFactory validatorFactory = Validation.byProvider(HibernateValidator.class)
                .configure()
                .failFast(true)
                .buildValidatorFactory();
        Validator validator = validatorFactory.getValidator();

        return validator;
    }


    /**
     * 接口请求拦截配置
     *
     * @param registry
     */
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addRedirectViewController("/", "/html/index.html");
    }

    @Value("${file.upload.location}")
    private String location;

    @Value("${file.upload.accessPath}")
    private String accessPath;


    /**
     * 虚拟路径配置
     *
     * @param registry
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
        registry.addResourceHandler(accessPath + "**").addResourceLocations("file:" + location);
    }

}

